/*
SMTP Protocol Handler

Copyright (C) 2007  Carlos Daniel Ruvalcaba Valenzuela <clsdaniel@gmail.com>

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/

#include <libfmail.h>

const int SMTP_PORT = 12000; //25;
const char CRLF[2] = {0x0D, 0x0A};

const int CMD_EHLO = 1;
const int CMD_HELO = 2;
const int CMD_MAIL = 3;
const int CMD_RCPT = 4;
const int CMD_DATA = 5;
const int CMD_QUIT = 6;
const int CMD_RSET = 7;
const char KEY_END_DATA[6] = {0x0D, 0x0A, '.', 0x0D, 0x0A, 0x00};

int knhash(char v){
    if ((v >= 65) && (v <= 90))
        return v - 65;
    
    if (v == 95)
        return 26;
    
    if ((v >= 97) && (v <= 122))
        return v - 97;
    
    if (v == ' ')
        return -1;
    
    if (v == 0x0D)
        return -1;
        
    return 255;
}

class SMTPHandler : public ProtocolHandler{
    SearchTree<int, 27, &knhash> cmdtree;
public:
    SMTPHandler(){
        cmdtree.Insert("EHLO", 1);
        cmdtree.Insert("HELO", 2);
        cmdtree.Insert("MAIL", 3);
        cmdtree.Insert("RCPT", 4);
        cmdtree.Insert("DATA", 5);
        cmdtree.Insert("QUIT", 6);
        cmdtree.Insert("RSET", 7);
    }
    int Handle(Socket *s){
        char buffer[255], username[255];
        int r, l;
        int onrun, cmd, state;
        FILE *fd;
	    
        state = 0;
        onrun = 1;
        cmd = 0;
        
        s->Write("220 FancyMail v0.1", 18);
        s->Write( CRLF, 2);
	    
        while (onrun){
            memset(buffer, 0, 255);
            r = s->Read(buffer, 255);
	        
            try{
                cmd = cmdtree.Lookup(buffer);
            }catch (SearchNotFound){
                cmd = -1;
            }
            
            switch(cmd){
                case CMD_HELO:
                    s->Write("250 ok localhost", 16);
                    s->Write(CRLF, 2);
                    state = 1;
                    break;
                case CMD_EHLO:
                    s->Write( "502 Not implemented", 19);
                    s->Write( CRLF, 2);
                    break;
                case CMD_MAIL:
                    if (state != 1){
                        s->Write( "502 Not implemented", 19);
                        s->Write( CRLF, 2);
                        break;
                    }
                    sprintf(username, "%s", (char*)(buffer+strlen("MAIL TO:")+1));
                    printf("Sending Mail TO: %s\n", username);
                    s->Write( "250 OK", 6);
                    s->Write( CRLF, 2);
                    state = 2;
                    break;
                case CMD_RCPT:
                    if (state != 2){
                        s->Write( "502 Not implemented", 19);
                        s->Write( CRLF, 2);
                        break;
                    }
                    printf("Recipent: %s\n", buffer);
                    s->Write( "250 OK", 6);
                    s->Write( CRLF, 2);
                    state = 3;
                    break;
                case CMD_DATA:
                    if (state != 3){
                        s->Write( "502 Not implemented", 19);
                        s->Write( CRLF, 2);
                        break;
                    }
                    printf("Reciving Data!\n");
                    s->Write( "354 OK", 6);
                    s->Write( CRLF, 2);
			
                    //fd = tmpfile();
			
                    r = 1;
                    while (r){
                        memset(buffer, 0, 255);
				
                        l = s->Read( buffer, 255);
                        printf("%s", buffer);
		    		
                        if (strstr(buffer, KEY_END_DATA)){
                            r = 0;
                            printf("\nEnd of Data\n");
                        }else{
                            printf("Buffer[%i]: %s\n", l, buffer);
                        }
                    }
                    
			
                    s->Write( "250 OK", 6);
                    s->Write( CRLF, 2);
                    state = 1;
                    break;
                case CMD_RSET:
                    s->Write( "250 OK", 6);
                    s->Write( CRLF, 2);
                    state = 1;
                    break;
                case CMD_QUIT:
                    printf("Got Quit, Exiting\n");
                    s->Write( "221 Exiting", 11);
                    s->Write(CRLF, 2);
                    onrun = 0;
                    break;
                default:
                    printf("Not implemented [State: %i]: %s\n", state, buffer);
                    s->Write( "502 Not implemented", 19);
                    s->Write( CRLF, 2);
                    break;
            }
		
            printf("Got: %s\n", buffer);
        }
        
        printf("Closing Connection\n");
        s->Close();
    }
};

#ifdef STANDALONE
class SimpleLoad : public LoadHandler {
public:
    int Dispatch(Socket *sock, ProtocolHandler *ph){
        if (ph)
            return ph->Handle(sock);
        return 0;
    }
};

int main(int argc, char **argv){
	BaseServer *srv;
	SimpleLoad *lh;
	SMTPHandler *handler;

	handler = new SMTPHandler();
	lh = new SimpleLoad();
	srv = new BaseServer(handler, SMTP_PORT);
	srv->SetLoadhandler(lh);
	srv->Listen();

	while(1){
		srv->Accept();
	}

	return 0;
}

#endif

extern "C"{
ProtocolHandler *plugin_protocol_load(){
    return new SMTPHandler();
}
}
